package top.btcmarket;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author hexj
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2018/4/211:43
 */
public class RSAEncrypt {


    /** *//**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 53;

    /** *//**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 64;

    public static byte[] encryptByPublicKey(byte[] publicKey, String data)
            throws Exception {
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);
        Cipher cipher = Cipher.getInstance("RSA");
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * 公钥加密
     * @param pubKey
     * @param input
     * @return
     * @throws Exception
     */
    public static  byte[] encrypt(byte[] pubKey,byte[] input) throws Exception {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(pubKey);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey publicKey = kf.generatePublic(spec);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(input);
    }

    /**
     * 私钥解密
     * @param priKey
     * @param cipherText 需要解密的密文
     * @return
     * @throws Exception
     */
    public static String decrypt(byte[] priKey,byte [] cipherText) throws Exception{
        KeyFactory kf = KeyFactory.getInstance("RSA");
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        PKCS8EncodedKeySpec sp =new PKCS8EncodedKeySpec(priKey);
        PrivateKey privateKey = kf.generatePrivate(sp);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] plainText = cipher.doFinal(cipherText);
        return new String(plainText);
    }

    public static byte[] decryptByPrivateKey(byte[] privateKey,byte[] encryptedData)
            throws Exception {
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Cipher cipher = Cipher.getInstance("RSA");
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    public static void main(String[] args) throws Exception {
        String prikey= "MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAvjSAzqDMQLQjtWrLm7+6d97FsP0Q" +
                "                                                            bIOKSXKsuu0y5EFjDL5xPEyrNg76aVQfHclA38A0KaujAWrLI5lOAackIwIDAQABAkB8aTUzcoQH" +
                "                                                            cozE1mT1rBQY4hMnMHA0ulmSrzqCTjJyj5tNGfYZo4ZS9ifLVwuY/BZQflcMXlisM2LsnMG4mjwx" +
                "                                                            AiEA+18WCSGMuqDRvNUCrDTeADuDQqLzd4LgTqPb/mxju6sCIQDBtRdjazxxg8GldWoKsWfO0YmV" +
                "                                                            mHvPoV578xb9Y4qBaQIgLlJ2cBZTpayvGdozFOLlKivNY4E91n8ysKs3hioZMuMCICClSXTK7Nvg" +
                "                                                            rbEZ8a4tqeYUMFDS6wLaGldfZ596uCwJAiBwn/1Ookhrl8xB7VI60fuFo6gYQOaWV+vnGKhZ348y" +
                "                                                            EQ==";
        String pubkey="MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAODg768VIgTgIDaKdSk+hGmXDsRUCAfUzq6kYLE0gh79pLEgag4vhKgk/UeAjoglLZ3L5UvoggdX5oZMa1RGeH0CAwEAAQ==";

        KeyGenerater keyGenerater = new KeyGenerater();
        byte[] pubKey = keyGenerater.getPubKey();
        byte[] priKey = keyGenerater.getPriKey();
        /*String pubkey=Base64.encodeBase64String(pubKey);
        String prikey=Base64.encodeBase64String(priKey);*/

        String ss="ji3UFQ+Ej8otgjUZCHGRqxy2MxmC0NFuPHl3skT6IysIM4I8h+7w00+avdp7TCBKKJd/l/hVofqqC0F6eF8fBA==";
  /*      byte[] bytes = encryptByPublicKey(Base64.decodeBase64(pubkey), ss);
        System.out.println(Base64.encodeBase64String(bytes));*/

        byte[] x = decryptByPrivateKey(Base64.decodeBase64(prikey), Base64.decodeBase64(ss));
      //  byte[] pukKey2 = RSAEncrypt.decryptByPrivateKey(priKey,Base64.decodeBase64(clientKey));

        System.out.println(new String(x));

    }

}
